package cn.wmw.xyy.service.impl;

import cn.wmw.xyy.constants.CacheConstant;
import cn.wmw.xyy.domain.CourseChapter;
import cn.wmw.xyy.domain.CourseType;
import cn.wmw.xyy.exception.GlobalExceptionEnum;
import cn.wmw.xyy.mapper.CourseTypeMapper;
import cn.wmw.xyy.service.ICourseTypeService;
import cn.wmw.xyy.utils.AssertUtil;
import cn.wmw.xyy.vo.CourseCrumbsVo;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author wmw
 * @since 2022-12-31
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    private static final Map<String, Object> cache = new HashMap<>();

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 课程分类树查询
     * @return
     */
    @Override
    @Cacheable(cacheNames = CacheConstant.COURSE_TYPE_CACHE_NAMES, key = CacheConstant.COURSE_TYPE_CACHE_KEY)
    public List<CourseType> treeData() {
        // Object o = cache.get(CacheConstant.COURSE_TYPE_TREE_DATA_KEY);
//        Object o = redisTemplate.opsForValue().get(CacheConstant.COURSE_TYPE_TREE_DATA_KEY);
//        if (o == null){ // 没有
//            log.info("缓存中不存在，走MySql!");
//            return getTreeData();
//        }else { // 有 服务之间调用，从Redis中获取如果涉及到要强转，那么必须使用JSON进行转换
//            log.info("缓存中存在，走Redis!");
//            List<CourseType> courseTypes = JSON.parseArray(JSONObject.toJSONString(o), CourseType.class);
//            return courseTypes;
//        }
        return getTreeData();
    }

    @Override
    public List<CourseCrumbsVo> crumbs(Long id) {
        // 1.参数校验
        // 2.业务校验
        CourseType courseType = selectById(id);
        AssertUtil.isNotNull(courseType, GlobalExceptionEnum.ERROR);
        // 3.查询面包屑数据
        String[] split = courseType.getPath().split("\\.");
        // 3.1.将所有要查询的类型的Id转换为Long集合
        List<Long> ids = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList());
        // 3.2.根据Id查询所有一级分类
        List<CourseType> ownerProductTypes = selectBatchIds(ids);
        // 3.3.遍历所有一级，查询所有同级，再封装到面包屑vo中
        List<CourseCrumbsVo> courseCrumbsVos = new ArrayList<>();

        ownerProductTypes.forEach(e->{
            // 1.根据pid查询当前一级的所有同级
            Wrapper<CourseType> wrapper = new EntityWrapper<>();
            wrapper.eq("pid", e.getPid());
            List<CourseType> courseTypes = selectList(wrapper);
            CourseCrumbsVo courseCrumbsVo = new CourseCrumbsVo(e, courseTypes);
            courseCrumbsVos.add(courseCrumbsVo);
        });
        return courseCrumbsVos;
    }

    private List<CourseType> getTreeData() {
        List<CourseType> courseTypes = selectList(null);
        Map<Long, CourseType> courseTypeMap = courseTypes.stream().collect(Collectors.toMap(CourseType::getId, courseType -> courseType));
        List<CourseType> treeData = new ArrayList<>();
        courseTypes.forEach(e->{
            if (e.getPid() == null || e.getPid() == 0){
                treeData.add(e);
            }else {
                CourseType courseType = courseTypeMap.get(e.getPid());
                if (courseType != null){
                    courseType.getChildren().add(e);
                }
            }
        });
        // cache.put(CacheConstant.COURSE_TYPE_TREE_DATA_KEY, treeData);
        // redisTemplate.opsForValue().set(CacheConstant.COURSE_TYPE_TREE_DATA_KEY, treeData);
        return treeData;
    }

    @Override
    @CacheEvict(cacheNames = CacheConstant.COURSE_TYPE_CACHE_NAMES, key = CacheConstant.COURSE_TYPE_CACHE_KEY)
    public boolean insert(CourseType entity) {
//        boolean insert = super.insert(entity);
//        isGetTreeData(insert);
        return super.insert(entity);
    }

    @Override
    @CacheEvict(cacheNames = CacheConstant.COURSE_TYPE_CACHE_NAMES, key = CacheConstant.COURSE_TYPE_CACHE_KEY)
    public boolean updateById(CourseType entity) {
//        boolean updateById = super.updateById(entity);
//        isGetTreeData(updateById);
        return super.updateById(entity);
    }


    @Override
    @CacheEvict(cacheNames = CacheConstant.COURSE_TYPE_CACHE_NAMES, key = CacheConstant.COURSE_TYPE_CACHE_KEY)
    public boolean deleteById(Serializable id) {
//        boolean deleteById = super.deleteById(id);
//        isGetTreeData(deleteById);
        return super.deleteById(id);
    }

    private void isGetTreeData(boolean deleteById) {
        if (deleteById) {
            this.getTreeData();
        }
    }

}
